#!/usr/bin/env bash
#部署脚本，参考module6

set -euo pipefail

#$(dirname "$0")没有生效，这里写死，注意更改
basedir="/home/baiyunlong/module8/deployment"
keydir="$(mktemp -d)"

# Generate keys into a temporary directory.
echo "Generating TLS keys ..."
"${basedir}/generate-keys.sh" "$keydir"


echo "Creating Kubernetes objects ..."
kubectl create namespace httpserver

# Create the TLS secret for the generated keys.
kubectl -n httpserver create secret tls httpserver-tls \
    --cert "${keydir}/httpserver-tls.crt" \
    --key "${keydir}/httpserver-tls.key"

# Read the PEM-encoded CA certificate, base64 encode it, and replace the `${CA_PEM_B64}` placeholder in the YAML
# template with it. Then, create the Kubernetes resources.
ca_pem_b64="$(openssl base64 -A <"${keydir}/ca.crt")"
sed -e 's@${CA_PEM_B64}@'"$ca_pem_b64"'@g' <"${basedir}/homework02.yaml" \
    | kubectl create -f -

# Delete the key directory to prevent abuse (DO NOT USE THESE KEYS ANYWHERE ELSE).
rm -rf "$keydir"

echo "The httpserver has been deployed and configured!"
